﻿import { InfoCircleOutlined } from '@ant-design/icons';
import { message as messageModal, Modal } from 'antd';
import { getIntl } from 'umi';
import { responseHandler } from './../requestErrorConfig';

const { confirm } = Modal;

const fileDownload = (res, filename) => {
  let blob = new Blob([res.data]); // 将返回的数据通过Blob的构造方法，创建Blob对象
  if ('msSaveOrOpenBlob' in navigator) {
    window.navigator.msSaveOrOpenBlob(blob, filename); // 针对浏览器
  } else {
    const elink = document.createElement('a'); // 创建a标签
    elink.download = filename;
    elink.style.display = 'none';
    // 创建一个指向blob的url，这里就是点击可以下载文件的根结
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href); //移除链接
    document.body.removeChild(elink); //移除a标签
  }
};

interface DlOptionProps {
  responseType: string;
  getResponse: boolean;
}

type DownloadFun = (params: object | undefined, option: DlOptionProps) => void;

let lock = false;
// 文件下载
export const downloadFetch = async (downloadFile: DownloadFun, params?: { [key: string]: any }) => {
  if (lock) {
    return;
  }
  lock = true;
  const hide = messageModal.loading(
    getIntl().formatMessage({
      id: 'global.fileReady',
    }),
    0,
  );
  try {
    const res = await downloadFile(params, {
      responseType: 'blob',
      getResponse: true,
    });

    hide();

    if (res?.data?.type === 'application/json') {
      const reader = new FileReader();
      reader.readAsText(res?.data, 'utf-8');
      reader.onload = function () {
        const result = JSON.parse(reader?.result);
        responseHandler({
          ...res,
          data: result,
          config: {
            ...res.config,
            downloadFun: () => {
              downloadFetch(downloadFile, params);
            },
          },
        });
      };
      lock = false;
    } else if (res?.status) {
      confirm({
        title: getIntl().formatMessage({
          id: 'systemManagement.supplementary.prompt',
        }),
        icon: <InfoCircleOutlined style={{ color: '#1a6cfe' }} />,
        content: getIntl().formatMessage({
          id: 'systemManagement.supplementary.theFileIsReady',
        }),
        okText: getIntl().formatMessage({
          id: 'systemManagement.supplementary.downloadNow',
        }),
        cancelText: getIntl().formatMessage({
          id: 'systemManagement.supplementary.cancelDownload',
        }),
        onOk: async () => {
          const name = decodeURIComponent(res.headers['content-disposition']?.split('=')[1]);
          if (name) {
            fileDownload(res, name);
          }
        },
        afterClose: () => {
          lock = false;
        },
      });
    } else {
      messageModal.error(
        getIntl().formatMessage({
          id: 'login.sysPrompt',
        }),
      );
      lock = false;
    }
  } catch (error) {
    hide();
    lock = false;
    console.error(error);
    messageModal.error(
      getIntl().formatMessage({
        id: 'login.sysPrompt',
      }),
    );
  }
};
